const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');

const PORT = 8080;
const UPLOAD_DIR = path.join(__dirname, 'static', 'uploads');

// 确保上传目录存在
if (!fs.existsSync(UPLOAD_DIR)) {
    fs.mkdirSync(UPLOAD_DIR, { recursive: true });
}

// 简单的文件上传处理
function handleFileUpload(req, res) {
    let body = '';
    
    req.on('data', chunk => {
        body += chunk.toString();
    });
    
    req.on('end', () => {
        try {
            // 简单的文件上传模拟
            const boundary = req.headers['content-type'].split('boundary=')[1];
            const parts = body.split(`--${boundary}`);
            
            for (let part of parts) {
                if (part.includes('filename=')) {
                    const filenameMatch = part.match(/filename="([^"]+)"/);
                    if (filenameMatch) {
                        const filename = filenameMatch[1];
                        const fileData = part.split('\r\n\r\n')[1];
                        
                        // 保存文件
                        const filePath = path.join(UPLOAD_DIR, filename);
                        fs.writeFileSync(filePath, fileData);
                        
                        res.writeHead(200, { 'Content-Type': 'application/json' });
                        res.end(JSON.stringify({ 
                            success: true, 
                            message: '文件上传成功',
                            filename: filename,
                            url: `/uploads/${filename}`
                        }));
                        return;
                    }
                }
            }
            
            res.writeHead(400, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ success: false, message: '未找到文件数据' }));
        } catch (error) {
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ success: false, message: error.message }));
        }
    });
}

// 获取图片列表
function getImagesList() {
    try {
        const files = fs.readdirSync(UPLOAD_DIR);
        return files.filter(file => {
            const ext = path.extname(file).toLowerCase();
            return ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg'].includes(ext);
        }).map(file => ({
            name: file,
            url: `/uploads/${file}`,
            size: fs.statSync(path.join(UPLOAD_DIR, file)).size
        }));
    } catch (error) {
        return [];
    }
}

// 简单的静态文件服务器
function serveStaticFile(req, res) {
    const parsedUrl = url.parse(req.url);
    let pathname = parsedUrl.pathname;
    
    // 默认首页
    if (pathname === '/') {
        pathname = '/upload-test.html';
    }
    
    // 移除开头的斜杠
    const safePath = pathname.substring(1);
    
    // 安全检查
    if (safePath.includes('..')) {
        res.writeHead(403, { 'Content-Type': 'text/plain' });
        res.end('403 Forbidden');
        return;
    }
    
    // 确定文件路径
    let filePath;
    if (safePath.startsWith('uploads/')) {
        filePath = path.join(__dirname, 'static', safePath);
    } else {
        filePath = path.join(__dirname, safePath);
    }
    
    // 如果文件不存在，尝试在static目录中查找
    if (!fs.existsSync(filePath)) {
        const staticPath = path.join(__dirname, 'static', safePath);
        if (fs.existsSync(staticPath)) {
            filePath = staticPath;
        }
    }
    
    if (!fs.existsSync(filePath)) {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 Not Found');
        return;
    }
    
    // 获取文件扩展名
    const ext = path.extname(filePath).toLowerCase();
    const contentTypes = {
        '.html': 'text/html',
        '.css': 'text/css',
        '.js': 'application/javascript',
        '.json': 'application/json',
        '.png': 'image/png',
        '.jpg': 'image/jpeg',
        '.jpeg': 'image/jpeg',
        '.gif': 'image/gif',
        '.svg': 'image/svg+xml',
        '.ico': 'image/x-icon'
    };
    
    const contentType = contentTypes[ext] || 'application/octet-stream';
    
    fs.readFile(filePath, (err, data) => {
        if (err) {
            res.writeHead(500, { 'Content-Type': 'text/plain' });
            res.end('500 Internal Server Error');
            return;
        }
        
        res.writeHead(200, { 
            'Content-Type': contentType,
            'Cache-Control': 'no-cache'
        });
        res.end(data);
    });
}

// 创建HTTP服务器
const server = http.createServer((req, res) => {
    // 设置CORS头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    
    if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
    }
    
    const parsedUrl = url.parse(req.url, true);
    
    // API路由
    if (parsedUrl.pathname === '/api/upload' || parsedUrl.pathname === '/api/upload-image') {
        if (req.method === 'POST') {
            handleFileUpload(req, res);
        } else {
            res.writeHead(405, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ success: false, message: '方法不允许' }));
        }
    } else if (parsedUrl.pathname === '/api/images') {
        if (req.method === 'GET') {
            const images = getImagesList();
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ 
                success: true, 
                images: images,
                count: images.length
            }));
        } else {
            res.writeHead(405, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ success: false, message: '方法不允许' }));
        }
    } else {
        // 静态文件服务
        serveStaticFile(req, res);
    }
});

server.listen(PORT, () => {
    console.log(`🚀 服务器启动成功！`);
    console.log(`📍 访问地址: http://localhost:${PORT}`);
    console.log(`📁 上传目录: ${UPLOAD_DIR}`);
    console.log(`🌐 测试页面: http://localhost:${PORT}/static/upload-test.html`);
});

// 优雅关闭
process.on('SIGINT', () => {
    console.log('\n👋 正在关闭服务器...');
    server.close(() => {
        console.log('✅ 服务器已关闭');
        process.exit(0);
    });
});